import React, { Component, PropTypes } from 'react'
import { exportFile, fetchPost } from '../../../utils/request'

import {
  Table,
  message,
  Button,
  Form,
  Input,
  Modal,
  Select,
  Card
} from 'antd'
import moment from 'moment'
import Styles from './Index.less'
import DlButton from '../../common/components/download/DlButton'

const FormItem = Form.Item
const Option = Select.Option

/**
 * 逾期分单列表
 */
class List extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      userId: null,
      params: props.params,
      list: [],
      loading: false,
      page: {
        currentPage: 1,
        pageSize: 100,
        totalCount: null
      },
      clickRowId: null,
      selectedRowKeys: [],
      selectRows: [],
      visible: false,
      overdueAdminList: [],
      appNameList: [],
      currentIndex: 0

    }
  }

  componentDidMount () {
    this.getData()
    this.getAdminCollectionList()
    this.getAppNamesList()
  }

  componentWillReceiveProps (props) {
    if (props.params != this.state.params) {
      this.setState({
        params: props.params
      }, () => {
        this.getData()
      })
    }
  }

  getData () {
    this.setState({
      loading: true
    })

    let currentPage = this.state.page.currentPage
    let pageSize = this.state.page.pageSize
    let copyParams = {}
    for (let i in this.state.params) {
      let value = this.state.params[i]
      if (!value) {
        copyParams[i] = null
      } else {
        copyParams[i] = value
      }
    }

    fetchPost(
      `/collection/v2/overdueOrderGet/list?currentPage=${currentPage}&pageSize=${pageSize}`,
      copyParams).then(json => {
      let list = json.data.itemList
      if (json.code === 0) {
        if (list.length > 0) {
          this.setState({
            userId: list[0].tradeNo,
            collectionNo: list[0].collectionNo,
            list,
            page: json.page,
            loading: false,
            selectedRowKeys: []
          }, () => {
            this.props.changeField({
              userId: list[0].tradeNo,
              item: list[0]
            })
          })
        } else {
          this.setState({
            userId: null,
            list: [],
            loading: false,
            page: {
              currentPage: 1,
              pageSize: 100,
              totalCount: null
            },
            selectedRowKeys: []
          }, () => {
            this.props.changeField({
              userId: null,
              item: {}
            })
          })
        }
      } else {
        message.error(json.msg)
        this.setState({
          userId: null,
          list: [],
          loading: false,
          page: {
            currentPage: 1,
            pageSize: 100,
            totalCount: null
          },
          selectedRowKeys: []
        }, () => {
          this.props.changeField({
            userId: null,
            item: {}
          })
        })
      }
    })
  }

  // 导出excel
  exportFile () {
    let copyParams = {}
    for (let i in this.state.params) {
      let value = this.state.params[i]
      if (!value) {
        copyParams[i] = null
      } else {
        copyParams[i] = value
      }
    }
    exportFile('/collection/v2/overdueOrderGet/export', `data-${moment().format('YYYY-MM-DD')}.xls`, copyParams)
  }

  getAdminCollectionList () {
    fetchPost('/collection/v2/agent/query', {}).then(json => {
      if (json.code === 0) {
        let list = json.data.itemList
        if (list !== null && list.length > 0) {
          this.setState({
            overdueAdminList: list
          }, () => {
            this.props.changeField({
              overdueAdminList: list
            })
          })
        }
      } else {
        message.error(json.msg)
      }
    })
  }

  getAppNamesList () {
    var queryKey = "appNameList";
    fetchPost(`/bizStats/general/query`, {queryKey}).then(json => {

      if (json && json.data != null && JSON.stringify(json.data) != '{}' && json.code === 0) {
        let data = json.data[queryKey]
        this.setState({
          appNameList: data,
        },() => {
          this.props.changeField({
            appNameList: data
          })
        })
      }
    });
  }

  nextpage (current) {
    this.setState({
      page: {
        ...this.state.page,
        currentPage: current
      }
    }, () => {
      this.getData()
    })
  }

  // 单击行
  handleClickRow (record, index) {
    this.setState({
      userId: record.tradeNo,
      collectionNo: record.collectionNo,
      currentIndex: index
    }, () => {
      this.props.changeField({
        userId: record.tradeNo,
        collectionNo: record.collectionNo,
        item: record
      })
    })
  }

  // 单击行，样式改变
  handleChosedRow (itemId, index) {
    if (index === this.state.currentIndex) {
      return Styles.active
    } else {
      return ''
    }
  };

  isShow (record) {
    return false
    // if (record.followUp === null) {
    //   return false
    // }
    // return true
  }

  batchDistribute () {
    // if (this.state.params.isNewAdd == null) {
    //   message.error('Please select New loan or Old loan')
    //   return
    // }

    // if (this.state.params.isAllocation == null ||
    //   this.state.params.isAllocation == 1) {
    //   message.error('Please select distribute order status: Unallocated')
    //   return
    // }

    this.setState({
      visible: true
    })
  }

  getOverdueAdmin (formItemLayout, getFieldDecorator) {
    if (this.state.overdueAdminList != null &&
      this.state.overdueAdminList.length > 0) {
      let content = []
      this.state.overdueAdminList.map(function (item) {
        content.push(
          <Option key={item.followId}
                  value={`${item.followId.toString()}|${item.name}`}>{item.name}</Option>
        )
      })
      return <FormItem
        {...formItemLayout}
        label='Collector'
      >
        {getFieldDecorator('followId', {
          initialValue: '',
          rules: [{ required: true, message: 'Please select your follow!' }]
        })(
          <Select placeholder='Collector'
                  style={{ width: 230 }}
                  showSearch={true}
                  optionFilterProp="children"
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >
            <Option value=''>Please Select</Option>
            {content}
          </Select>
        )}
      </FormItem>
    }
    return ''
  }

  showDetail () {
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    }
    return <div>
      <Form horizontal onSubmit={this.handleSubmit}
            style={{ marginTop: 15, width: '90%' }}>

        {this.getOverdueAdmin(formItemLayout, getFieldDecorator)}

        {/* <FormItem */}
        {/*  {...formItemLayout} */}
        {/*  label='Rate' */}
        {/* > */}
        {/*  {getFieldDecorator('externalRate', { */}
        {/*      initialValue: '0.00', */}
        {/*      rules: [ */}
        {/*        { */}
        {/*          required: true, */}
        {/*          message: 'Please input your externalRate!', */}
        {/*        }], */}
        {/*    }, */}
        {/*  )( */}
        {/*    <Input placeholder='Between 0 and 1'/>, */}
        {/*  )} */}
        {/* </FormItem> */}

        {/* <FormItem */}
        {/*  {...formItemLayout} */}
        {/*  label='Batch No' */}
        {/* > */}
        {/*  {getFieldDecorator('batchNo', { */}
        {/*    rules: [{required: true, message: 'Please input your batchNo!'}], */}
        {/*  })( */}
        {/*    <Input placeholder='Eg：20160824hf001'/>, */}
        {/*  )} */}
        {/* </FormItem> */}
      </Form>
    </div>
  }

  handleCancel () {
    this.props.form.resetFields()
    this.setState({ visible: false })
  }

  distribute () {
    // 验证
    this.props.form.validateFieldsAndScroll((errors, values) => {
      if (errors) {
        return false
      }
      if (values.externalRate >= 1 || values.externalRate < 0) {
        message.error('Rate between 0 and 1！')
        return false
      }

      let tradeNos = this.state.selectRows.map((value, index) => (
        value.tradeNo
      ))
      let follow = values.followId.split('|')
      if (this.state.selectedRowKeys.length > 0) {
        fetchPost('/collection/v2/order/distribute', {
          followId: follow[0],
          followUp: follow[1],
          tradeNos
        }).then(json => {
          if (json.code === 0) {
            message.info('Distribute success')
            this.setState({
              selectedRowKeys: [],
              visible: false
            })
            this.props.form.resetFields()
            this.getData()
          } else {
            message.error(json.msg)
          }
        })
      }
    })
  }

  changePage (value) {
    if (!value) {
      value = 100
    }
    this.setState({
      page: {
        currentPage: 1,
        pageSize: value,
        totalCount: 1
      }
    }, () => {
      this.getData()
    })
  }

  render () {
    let self = this
    const columns = [
      {
        title: 'Product',
        dataIndex: 'productCategoryName',
        key: 'productCategoryName'
      },
      {
        title: 'Name',
        dataIndex: 'name',
        key: 'name'
      }, {
        title: 'Mobile',
        dataIndex: 'mobile',
        key: 'mobile'
      }, {
        title: 'Aadhaar No',
        key: 'identityNo',
        dataIndex: 'identityNo'
      }, {
        title: 'Loan Amount',
        key: 'realCapital',
        dataIndex: 'realCapital'
      }, {
        title: 'Total amount should repay',
        key: 'expireAmount',
        dataIndex: 'expireAmount'
      }, {
        title: 'Amount already paid',
        key: 'paidAmount',
        dataIndex: 'paidAmount'
      }, {
        title: 'Penalty amount',
        key: 'lateFee',
        dataIndex: 'lateFee'
      }, {
        title: 'Language',
        key: 'userLanguage',
        dataIndex: 'userLanguage'
      }, {
        title: 'OverdueDays',
        // key: 'overdueDays',
        // dataIndex: 'overdueDays',
        render: (text, record) => {
          return record.collectionOrderDetailVoList[0].overdueDays
        }
      }, {
        title: 'Follow Up',
        key: 'followUp',
        dataIndex: 'followUp'
      }
    ]

    const pagination = {
      total: self.state.page.totalCount,
      pageSize: self.state.page.pageSize,
      showSizeChanger: false,
      showQuickJumper: true,
      showTotal (total) {
        return `Total ${total} `
      },
      onChange (current) {
        self.nextpage(current)
      }
    }
    const selectedRowKeys = this.state.selectedRowKeys
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        let selectRows = []
        selectedRows.map(function (item) {
          selectRows.push(item)
        })
        this.setState({
          selectedRowKeys,
          selectRows
        })
      },
      getCheckboxProps: (record) => (
        {
          disabled: this.isShow(record)
        }
      )
    }

    const hasSelected = selectedRowKeys.length > 0
    const { getFieldDecorator } = this.props.form
    return (
      <div className='mt10'>
        <div className='ant-layout-container'>
          <div style={{ marginBottom: 16 }}>
            Number Of Pages：
            {
              getFieldDecorator('pagination', {
                initialValue: '100'
              })(
                <Select style={{ width: 100 }}
                        onChange={(e) => this.changePage(e)}>
                  {/*<Option value=''>Default</Option>*/}
                  <Option value='20'>20</Option>
                  <Option value='30'>30</Option>
                  <Option value='50'>50</Option>
                  <Option value='100'>100</Option>
                  <Option value='200'>200</Option>
                  <Option value='500'>500</Option>
                </Select>
              )
            }
            &nbsp;&nbsp;
            <Button type='primary' disabled={!hasSelected}
                    onClick={(e) => this.batchDistribute()}>Assign order</Button>
            <span style={{ marginLeft: 8 }}>{hasSelected
              ? `Chose ${selectedRowKeys.length} `
              : ''}</span>

            <DlButton icon='download' downloadParams={this.state.params}
                      downloadUrl='/collection/v2/overdueOrderGet/list/export'/>
          </div>
          <div>Remarks：The repaid amount and the outstanding amount are (principal + penalty interest)</div>
          <Card bodyStyle={{ padding: 0 }} noHovering>
            <Table
              key='collectionNo'
              pagination={pagination}
              columns={columns}
              dataSource={self.state.list}
              loading={self.state.loading}
              onRowClick={(record, index) => this.handleClickRow(record, index)}
              rowClassName={(record, index) => this.handleChosedRow(
                record.collectionNo, index)}
              bordered
              size='small'
              style={{ background: '#FFFFFF' }}
              rowSelection={rowSelection}
            />
          </Card>
          <Modal
            visible={this.state.visible}
            title='Overdue Distribute'
            onCancel={() => {
              this.handleCancel()
            }}
            footer={[
              <Button key='back' type='ghost' size='large'
                      onClick={() => {
                        this.handleCancel()
                      }}>Cancel</Button>,
              <Button key='submit' type='primary' size='large'
                      onClick={() => {
                        this.distribute()
                      }}>
                Distribute
              </Button>]}
          >
            {this.showDetail()}
          </Modal>

        </div>
      </div>
    )
  }
}

List = Form.create()(List)
export default List
